<?php

namespace app\common\service;

//use think\facade\Cache;
use yiovo\cache\facade\Cache;


class ShortSms
{
    //验证码可重复验证的次数
    protected int $checkTimes = 5;
    // 验证码过期时间（s）
    protected int $expire = 1800;

    /**
     * 生成短信验证码并把验证码的值保存的缓存中
     * @access public
     * @param string $phone
     * @return object
     */
    public function createSMS(string $phone): array
    {
        $code = (string)mt_rand(1000, 9999);
        Cache::set("captchaSMS.{$phone}", ['code' => $code, 'times' => $this->checkTimes], $this->expire);
        return ['key' => $phone, 'code' => $code];
    }

    /**
     * 验证短信验证码是否正确
     * @access public
     * @param string $code
     * @param string $phone
     * @return bool
     */
    public function checkSMS(string $code, string $phone): bool
    {
        $captcha = Cache::get("captchaSMS.{$phone}");
        if (empty($captcha)) {
            throwError('短信验证码不存在，请重新获取');
        }
        if ($captcha['times'] <= 0) {
            Cache::delete("captchaSMS.{$phone}");
            throwError('短信验证码已超出错误次数，请重新获取');
        }
        if ($captcha['code'] != $code) {
            Cache::update("captchaSMS.{$phone}", ['times' => $captcha['times'] - 1]);
            throwError('短信验证码不正确，请重新填写');
        }
        Cache::delete("captchaSMS.{$phone}");
        return true;
    }
}